import json
import os


class BaseConfigManager:
    """配置管理基类"""

    CONFIG_FILE = "network_config.json"  # 共享配置文件

    def __init__(self):
        self.config = self.load_config()

    def load_config(self):
        """加载配置文件"""
        if os.path.exists(self.CONFIG_FILE):
            try:
                with open(self.CONFIG_FILE, "r", encoding="utf-8") as f:
                    return json.load(f)
            except:
                return {}
        return {}

    def save_config(self):
        """保存配置文件"""
        with open(self.CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(self.config, f, indent=2, ensure_ascii=False)

    def update_config(self, config):
        """更新整个配置"""
        self.config = config
        self.save_config()


class NetworkConfigManager(BaseConfigManager):
    """网络配置管理子类"""

    CONFIG_SECTION = "network"

    def __init__(self):
        super().__init__()
        # 初始化网络配置区域
        if self.CONFIG_SECTION not in self.config:
            self.config[self.CONFIG_SECTION] = {}
            self.save_config()

    def is_first_time(self):
        """检查网络配置是否完整"""
        network_config = self.config.get(self.CONFIG_SECTION, {})
        return "internal" not in network_config or "external" not in network_config

    def set_network_config(self, network_type, config):
        """设置指定类型的网络配置"""
        network_config = self.config.get(self.CONFIG_SECTION, {})
        network_config[network_type] = config
        self.config[self.CONFIG_SECTION] = network_config
        self.save_config()

    def get_network_config(self, network_type):
        """获取指定类型的网络配置"""
        network_config = self.config.get(self.CONFIG_SECTION, {})
        return network_config.get(network_type, {})


class PrintConfigManager(BaseConfigManager):
    """打印机配置管理子类"""

    CONFIG_SECTION = "printers"
    GLOBAL_CONFIG_SECTION = "global_print_config"

    def __init__(self):
        super().__init__()
        # 初始化打印机配置区域
        if self.CONFIG_SECTION not in self.config:
            self.config[self.CONFIG_SECTION] = {}
            self.save_config()
        if self.GLOBAL_CONFIG_SECTION not in self.config:
            self.config[self.GLOBAL_CONFIG_SECTION] = {
                "default": {
                    "paper_size": "A4",
                    "orientation": "纵向",
                    "quality": "中",
                    "copies": 1
                }
            }
            self.save_config()

    def get_printers(self):
        """获取所有打印机配置"""
        return self.config.get(self.CONFIG_SECTION, {})

    def add_printer(self, name, ip, params=None):
        """添加或更新打印机配置"""
        printers = self.config.get(self.CONFIG_SECTION, {})
        printers[name] = {"ip": ip, "params": params or {}}
        self.config[self.CONFIG_SECTION] = printers
        self.save_config()

    def remove_printer(self, name):
        """移除打印机配置"""
        printers = self.config.get(self.CONFIG_SECTION, {})
        if name in printers:
            del printers[name]
            self.config[self.CONFIG_SECTION] = printers
            self.save_config()
            return True
        return False

    def get_printer(self, name):
        """获取特定打印机配置"""
        printers = self.config.get(self.CONFIG_SECTION, {})
        return printers.get(name)

    def update_printer_status(self, name, status):
        """更新打印机状态"""
        printers = self.config.get(self.CONFIG_SECTION, {})
        if name in printers:
            printers[name]["status"] = status
            self.config[self.CONFIG_SECTION] = printers
            self.save_config()
            return True
        return False

    def update_printer_params(self, name, params):
        """更新打印机参数"""
        printers = self.config.get(self.CONFIG_SECTION, {})
        if name in printers:
            printers[name]["params"] = params
            self.config[self.CONFIG_SECTION] = printers
            self.save_config()
            return True
        return False

    def get_printer_status(self, name):
        """获取打印机状态"""
        printers = self.config.get(self.CONFIG_SECTION, {})
        if name in printers:
            return printers[name].get("status", "unknown")
        return "unknown"

    def get_global_config(self):
        """获取全局打印配置"""
        return self.config.get(self.GLOBAL_CONFIG_SECTION, {})

    def update_global_config(self, file_type, config):
        """更新指定文件类型的全局配置"""
        global_config = self.config.get(self.GLOBAL_CONFIG_SECTION, {})
        global_config[file_type] = config
        self.config[self.GLOBAL_CONFIG_SECTION] = global_config
        self.save_config()
        return True

    def get_config_for_file(self, file_path):
        """根据文件路径获取对应的配置"""
        # 获取文件扩展名
        _, ext = os.path.splitext(file_path)
        ext = ext.lower()

        global_config = self.config.get(self.GLOBAL_CONFIG_SECTION, {})

        # 查找匹配的配置
        if ext in global_config:
            return global_config[ext]
        elif "default" in global_config:
            return global_config["default"]
        else:
            # 返回默认配置
            return {
                "paper_size": "A4",
                "orientation": "纵向",
                "quality": "中",
                "copies": 1
            }
